<template>
    <div>
        <el-dialog :title="title" :visible.sync="addVisible" :close-on-click-modal="false"
            :close-on-press-escape="false" @closed="handlerCancel()">
            <el-form :model="userInfo">
                <el-form-item label="id" :label-width="formLabelWidth" v-if="!isadd">
                    <el-input v-model="userInfo.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input v-model="userInfo.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="userInfo.password"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" :label-width="formLabelWidth">
                    <el-input v-model="userInfo.realName"></el-input>
                </el-form-item>
                <el-form-item label="昵称" :label-width="formLabelWidth">
                    <el-input v-model="userInfo.nickName"></el-input>
                </el-form-item>
                <el-form-item label="性别" :label-width="formLabelWidth">
                    <el-switch style="display: block" v-model="userInfo.gender" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"
                        active-text="男" inactive-text="女">
                    </el-switch>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth">
                    <el-input v-model="userInfo.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="头像" :label-width="formLabelWidth">
                    <el-upload class="avatar-uploader" action="/api/auth/user/upload" :show-file-list="false"
                        :headers="headers" name="face" :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handlerCancel()">取 消</el-button>
                <el-button type="primary" @click="handlerSave()">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { useInfByIdoApi,addUseApi,editUseApi } from '../../api/UseApi.js'
export default {
    props: ['addVisible', "title"],
    data() {
        return {
            userInfo: {
                id: 0,
                username: "",
                password: "",
                realName: "",
                nickName: "",
                gender: 1,
                phone: "",
                email: "",
                avatar: "",
            },
            isadd: false,
            formLabelWidth: '120px',
            headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }
        };
    },
    methods: {
        handlerCancel() {
            this.$emit('closeDialog');

        },
       async handlerSave() {
            if (this.isadd) {
                try {
                    const res = await addUseApi(this.userInfo);
                    if (res.status === 200) {
                        this.$message({
                            message: res.msg,
                            type: 'success',
                            duration: 1000,
                            onClose: () => {
                                this.$emit('closeDialog',true);
                            }
                        });
          
                    } else {
                        this.$message.error(res.msg);
                    }
                } catch (error) {
                    console.error('获取用户列表失败:', error);
                    this.$message.error('网络错误，请稍后重试');
                }

            }else{
                try {
                    const res = await editUseApi(this.userInfo);
                    if (res.status === 200) {
                        this.$message({
                            message: res.msg,
                            type: 'success',
                            duration: 1000,
                            onClose: () => {
                                this.$emit('closeDialog',true);
                            }
                        });
          
                    } else {
                        this.$message.error(res.msg);
                    }
                } catch (error) {
                    console.error('获取用户列表失败:', error);
                    this.$message.error('网络错误，请稍后重试');
                }

            }
            
        },
        handleAvatarSuccess(res, file) {
            if (res.status === 200) {
                const fileName = res.data.fileName;
                const hostName = res.data.hostName;
                this.userInfo.avatar = hostName + fileName;

            } else {
                this.$message.error(res.msg);
            }

        },
        async openDialog(userId) {
            if (!userId) {
                this.userInfo = {
                    id: 0,
                    username: "",
                    password: "",
                    realName: "",
                    nickName: "",
                    gender: 1,
                    phone: "",
                    email: "",
                    avatar: "",
                }
                this.isadd = true;
            } else {
                try {
                    this.isadd = false;
                    const res = await useInfByIdoApi(userId);
                    if (res.status === 200) {
                        this.userInfo = res.data;
                    } else {
                        this.$message.error(res.msg);
                    }
                } catch (error) {
                    console.error('获取用户列表失败:', error);
                    this.$message.error('网络错误，请稍后重试');
                }
                

            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }

    }
};

</script>
<style scoped lang="less">
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>